<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/3/10
 * Time: 14:07
 */

namespace app\server\push;
use app\server\request\Req;

class AppPush
{
    protected $appkey;
    protected $mastersecret;
    protected $req;
    protected $url;
    protected $appid;
    public function __construct()
    {
        $this->appid='****';
        $this->appkey='****';
        $this->mastersecret='****';
        $this->url='https://restapi.getui.com/v2/';

        $this->req=app()->make(Req::class);
    }

//获取个推的token
    public function getToken()
    {
        //先判断一下有没有缓存,缓存有没有过期,如果有缓存那么直接返回
        if(cache('pushtoken')){
            return cache('pushtoken');
        }
        $url =  $this->url.$this->appid.'/auth';
        $time=time()*1000;
        $data = [
            'sign' => hash("sha256", $this->appkey.$time.$this->mastersecret),
            "timestamp"=> $time,
            "appkey"=> $this->appkey
        ];
        $data = json_encode($data);
        $res=$this->req->postJson($url,$data);
        $res=json_decode($res);
        if($res->code==0){//获取成功,把token存进缓存,时间为过期前10分钟
            $ctime=($res->data->expire_time-$time)/1000-600;
            cache('pushtoken', $res->data->token, floor($ctime));
            return $res->data->token;
            //这里有点小问题,跑是没有问题的,如果没有获取到token的话应该会报错,调用的时候应该加一个如果没有返回token的话报错,这里就先不写啦,要用的自己补上
        }
    }

//单个的推送,其它的就自己写啦.
    public function pushCid($cid,$data='',$request_id=null){
        $token= $this->getToken();
        $url =  $this->url.$this->appid.'/push/single/cid';
        $push = [
            "request_id"=>$request_id??time(),
            "settings"=>["ttl"=>3600000],
            "audience"=>[ "cid"=>[ $cid]],
            "push_message"=>[
                "notification"=>[
                    //下面是php7点几的特性,部分低版本不能用,需要自己换成三元运算的
                    "title"=>$data['title']??"表情更新啦",
                    "body"=>$data['body']??"又更新了不少表情,来看一看么",
                    "click_type"=>$data['click_type']??"startapp",
                    "url"=>$data['url']??"cn.ibiaoqin.www",
                    'logo_url'=>$data['logo_url']??'',
                ] ]
        ];
        $push = json_encode($push);
        $res=$this->req->postJson($url,$push,$token);
        $res=json_decode($res);
       // var_dump($res);
        if($res->code==0)
            return ['code'=>1,'msg'=>'推送成功'];
        return ['code'=>0,'msg'=>'推送失败'];
    }
}